
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构
struct ListNode {
    int val;
    struct ListNode *next;
};
// 移除链表元素函数
struct ListNode* removeElements(struct ListNode* head, int val) {
    // 处理头节点为要删除的元素的情况
    while (head != NULL && head->val == val) {
        struct ListNode* temp = head;
        head = head->next;
        free(temp);
    }
    // 处理链表中间和尾部的节点
    struct ListNode* current = head;
    while (current != NULL && current->next != NULL) {
        if (current->next->val == val) {
            struct ListNode* temp = current->next;
            current->next = current->next->next;
            free(temp);
        } else {
            current = current->next;
        }
    }
    return head;
}
// 测试函数
void test() {
    // 创建链表 1->2->6->3->4->5->6
    struct ListNode* head = (struct ListNode*)malloc(sizeof(struct ListNode));
    head->val = 1;
    struct ListNode* node2 = (struct ListNode*)malloc(sizeof(struct ListNode));
    node2->val = 2;
    head->next = node2;
    struct ListNode* node3 = (struct ListNode*)malloc(sizeof(struct ListNode));
    node3->val = 6;
    node2->next = node3;
    struct ListNode* node4 = (struct ListNode*)malloc(sizeof(struct ListNode));
    node4->val = 3;
    node3->next = node4;
    struct ListNode* node5 = (struct ListNode*)malloc(sizeof(struct ListNode));
    node5->val = 4;
    node4->next = node5;
    
    struct ListNode* node6 = (struct ListNode*)malloc(sizeof(struct ListNode));
    node6->val = 5;
    node5->next = node6;
    
    struct ListNode* node7 = (struct ListNode*)malloc(sizeof(struct ListNode));
    node7->val = 6;
    node6->next = node7;
    node7->next = NULL;
    
    // 移除元素6
    int val = 6;
    struct ListNode* result = removeElements(head, val);
    
    // 打印移除元素后的链表
    struct ListNode* current = result;
    while (current != NULL) {
        printf("%d ", current->val);
        current = current->next;
    }
    printf("\n");
    
    // 释放链表内存
    current = result;
    while (current != NULL) {
        struct ListNode* temp = current;
        current = current->next;
        free(temp);
    }
}

int main() {
    test();
    return 0;
}

